/*	$Id$	*/
/*
 * Copyright (c) 2007 Jean-Francois Brousseau <phrakt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include <canopy/log.h>

#include "http.h"
#include "conn.h"
#include "proto.h"
#include "private.h"


/*
 * http_connect()
 *
 * Create a new stream socket and connect it to the remote address <addr>.
 * Returns the socket on success, or -1 on failure.
 */
int
http_connect(struct sockaddr *addr, socklen_t len)
{
	int s;

	if ((s = socket(addr->sa_family, SOCK_STREAM, 0)) == -1) {
		cnp_log(CNP_LOG_ERRNO, "failed to create stream socket");
		return (-1);
	}

	if (connect(s, addr, len) == -1) {
		return (-1);
	}

	return (s);
}

/*
 * http_bind()
 *
 * Create a new stream socket and bind it to the address <addr>.
 * Returns the socket on success, or -1 on failure.
 */
int
http_bind(struct sockaddr *addr, socklen_t len)
{
	int s, one = 1;
	size_t alen;
	char abuf[32];

	if (addr->sa_family == AF_INET) {
		inet_ntop(addr->sa_family,
		    &((struct sockaddr_in *)addr)->sin_addr, abuf,
		    sizeof(abuf));
		alen = strlen(abuf);
		snprintf(abuf + alen, sizeof(abuf) - alen, ":%u",
		    htons(((struct sockaddr_in *)addr)->sin_port));
	}

	if ((s = socket(addr->sa_family, SOCK_STREAM, 0)) == -1) {
		cnp_log(CNP_LOG_ERRNO, "failed to create socket");
		return (-1);
	}

	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1)
		cnp_log(CNP_LOG_WARN, "failed to make address reusable");

	if (bind(s, addr, len) == -1) {
		cnp_log(CNP_LOG_ERRNO, "failed to bind HTTP socket to %s",
		    abuf);
		(void)close(s);
		return (-1);
	}

	if (listen(s, 32) == -1) {
		cnp_log(CNP_LOG_ERR, "failed to listen on HTTP socket");
		(void)close(s);
		return (-1);
	}

	cnp_log(CNP_LOG_INFO, "ready to listen for HTTP requests on %s", abuf);

	return (s);
}

/*
 * http_accept()
 *
 * Accept incoming HTTP connections from any one of the sockets previously
 * opened by http_bind().
 */
http_conn_t*
http_accept(int sock, const struct timeval *timeout)
{
	int ret;
	size_t alen;
	char abuf[32];
	fd_set fds;
	struct timeval to, *top = NULL;
	struct http_conn *conn = NULL;

	if (timeout != NULL) {
		to.tv_sec = timeout->tv_sec;
		to.tv_usec = timeout->tv_usec;
		top = &to;

		FD_ZERO(&fds);
		FD_SET(sock, &fds);

		ret = select(sock + 1, &fds, NULL, NULL, top);
		if (ret == -1) {
			if (errno == EAGAIN)
				return (NULL);
		} else if (ret == 0)
			return (NULL);

		if (!FD_ISSET(sock, &fds))
			return (NULL);
	}

	if ((conn = http_conn_alloc(-1)) == NULL)
		return (NULL);

	if ((conn->hc_sock = accept(sock, &conn->hc_raddr,
	    &conn->hc_ralen)) == -1) {
		cnp_log(CNP_LOG_ERRNO, "failed to accept");
		free(conn);
		return (NULL);
	}

	if (conn->hc_raddr.sa_family == AF_INET) {
		inet_ntop(conn->hc_raddr.sa_family,
		    &((struct sockaddr_in *)&conn->hc_raddr)->sin_addr, abuf,
		    sizeof(abuf));
		alen = strlen(abuf);
		snprintf(abuf + alen, sizeof(abuf) - alen, ":%u",
		    htons(((struct sockaddr_in *)&conn->hc_raddr)->sin_port));
	}

	getsockname(conn->hc_sock, &conn->hc_laddr, &conn->hc_lalen);

	cnp_log(CNP_LOG_INFO, "accepted HTTP connection from %s", abuf);

	return (conn);
}
